/**
 * Created by LinJe on 2015/10/22.
 */
;(function( $, window ) {

    var olistUl = $('.list-content'),
        oLoadMore = $('.js-loadmore'),
        pageStep = 1, totalSize = -1, allowShowLine = true;

    //默认加载
    initLoad();

    //开启页面滚动到底部自动加载更多商品
    $.addScrollToBottom();
    $(window).on('scrollToBottom', function() {
        pageStep ++;
        var opts = {'insertFunction':'append', 'pageStep':pageStep, 'count':20};
        inserProductContent(opts, function( res ) {
            if ( res.scrollEnd ) {
                oLoadMore.removeClass('mtb300').addClass('mtb50').html('<span class="loading"><a>已经是最后一条内容</a></span>');
            } else {
                $.canloadInfo = true;
            }
        });
    });

    //点击回复 展开回复框
    olistUl.on('click', '.reply', function() {
        var userInfo = userServers.getUserInfo();

        if ( userInfo.userName ) {
            var thisReplay = $(this);

            //如果是第一次点击
            if ( !thisReplay.data('hasAppend') ) {
                addReplyBox( thisReplay.parent() );
                thisReplay.data('hasAppend', true);
            }
        } else {
            window.globalLayer.openLogin(); //打开登陆提示弹窗
        }
    });

    //回复评论的输入框
    olistUl.on('keydown', '.js-input-reply', function() {
        var thisInput = $(this),
            oSubmit = thisInput.parent().siblings('.button').find('.button-default');

        inputRule(thisInput, oSubmit);
    });
    olistUl.on('keyup', '.js-input-reply', function() {
        var thisInput = $(this),
            oSubmit = thisInput.parent().siblings('.button').find('.button-default');

        inputRule(thisInput, oSubmit);
    });

    //点击提交 回复的数据
    olistUl.on('click', '.textarea-block .button .button-default', function() {
        var userInfo = userServers.getUserInfo();

        if ( userInfo.userName ) {
            var thisButton = $(this),
                userAvatar = userInfo.userAvatar,
                userName = userInfo.userName;

            if ( !thisButton.hasClass('button-disabled') ) {
                var oParentLi = thisButton.parents('li').eq(1),
                    messageType = oParentLi.attr('_messagetype'),
                    replayerId = oParentLi.attr('_replayerid'),
                    messageId = oParentLi.attr('_messageid'),
                    ugcId = oParentLi.attr('_ugcId'),
                    oInput = thisButton.parents('.textarea-block').find('.js-input-reply');

                //向后端插入该条回复
                messageServer.addReply({
                    'cid': messageId,
                    'ugcId': ugcId,
                    'replayerId':replayerId,
                  'messageType': messageType,
                    'commentContent': oInput.val()
                }, function(msg) {
                    if ( msg.error || msg.code != 200 ) {
                        window.globalLayer.openWarning({'autoClose':true, time:1000, text:msg.description});
                        return;
                    }
                    window.globalLayer.openWarning({'autoClose':true, time:1000, text:msg.description});
                    oInput.val('');
                    thisButton.addClass('button-disabled');
                });
            }
        } else {
            window.globalLayer.openLogin(); //打开登陆提示弹窗
        }
    });


    //***********公用方法***************
    //初始化加载
    function initLoad() {
        pageStep = 1;
        totalSize = -1;
        oLoadMore.show().removeClass('mtb50').addClass('mtb300').html('<span class="loading"><a><i class="i-05"></i>正在加载更多</a></span>');
        var opts = {
            'insertFunction':'html',
            'pageStep': pageStep,
            'count': 20
        };
        inserProductContent(opts, function( res ) {

            if ( res && res.scrollEnd ) {
                //oLoadMore.hide();
                oLoadMore.removeClass('mtb300').addClass('mtb50').html('<span class="loading"><a>已经是最后一条内容</a></span>');
            }
        });
    }

    //输入框内容的规则限制
    function inputRule( $input, $button ) {
        //限制字数
        $.maxTextLen({
            'field': $input,
            'isSubStr': true,
            'callBack': function(data) {
                //是否激活提交按钮
                canActiveButton($button, data);
            }
        });
    }

    //判断是否能激活按钮
    function canActiveButton( $obj, boolean ) {
        if ( boolean ) {
            $obj.removeClass('button-disabled');
        } else {
            $obj.addClass('button-disabled');
        }
    }

    //插入商品内容
    function inserProductContent( opts, callBack ) {
        if ( totalSize != -1 && totalSize < pageStep ) {
            callBack && callBack({'scrollEnd':true});
            return;
        }
        messageServer.getProductData(opts, function( msg ) {
            if ( msg.code == 200 ) {
                //获取数据成功
                olistUl[opts.insertFunction]( getMoreHtml(msg.detail.messages) );
                totalSize = msg.detail.totalSize;
                callBack && callBack({'scrollEnd':totalSize<=1});
            } else {
                window.globalLayer.openWarning({'autoClose':true, time: 2000, text:msg.description});
                callBack && callBack({});
            }
        });
    }

    //获取多条商品的html
    function getMoreHtml( data ) {
        var totalHtml = '';

        for ( var i = 0, iLen = data.length; i < iLen; i ++ ) {
            totalHtml += getSingelHtml(data[i]);
        }
        return totalHtml;
    }

    //添加回复文本框
    function addReplyBox( $obj ) {
        $obj.after('<div class="textarea-block">\
                        <div class="textarea">\
                            <textarea name="" class="js-input-reply"></textarea>\
                        </div>\
                        <div class="button">\
                            <button type="button" class="button-default button-disabled">回复</button>\
                        </div>\
                    </div>');
    }


    //获取单条商品的html
    function getSingelHtml( data ) {
        return (function(){
                var str = '';
                if ( data.isRead == 1 && allowShowLine ) {
                    allowShowLine = false;
                    str = '<div class="title-concise"><span>以下是历史消息</span></div>';
                }
                return str;
            })()+'<li _messagetype="'+ data.messageType +'" _replayerid="'+ data.replayUserId +'" _messageid="'+ data.replayId +'" " _ugcId="'+ data.ugcId +'">\
                    <div class="w-opt"> <span class="time">'+ data.replayTime +'</span></div>\
                    <div class="goods-description-comment">\
                      <div class="comment">\
                        <div class="content">\
                          <div class="list">\
                            <ul>\
                              <li>\
                                <div class="user-avatar"><a href="'+ data.replayUrl +'"><img src="'+ data.replayAvatar +'" width="30" height="30"></a></div>\
                                <div class="con">\
                                  <p><span class="user-name"><a href="'+ data.replayUrl +'">'+ data.replayName +'</a></span>：'+ data.replayMessage +'</p>\
                                  <div class="w-opt">'+ (function() {
                                    //此处判断该条评论是否为当前用户所有，如果是，则不输出回复功能，否则输出
                                    return data.replayUserId != userServers.getUserInfo().userId ? '<span class="reply"><a href="javascript:;">回复</a></span>' : '';
                                })() +'</div>\
                                  <div class="wb-comment">\
                                    <h6>'+ data.replayDescription +'</h6>\
                                    <p><a href="'+ data.ugcUrl +'" target="_Blank">'+ data.myMessage +'</a></p>\
                                  </div>\
                                </div>\
                              </li>\
                            </ul>\
                          </div>\
                        </div>\
                      </div>\
                      <div class="bottom"></div>\
                    </div>\
                 </li>';
    }

})( jQuery, window );